package com.duoduo.controller.admin;


import com.duoduo.constant.MessageConstant;
import com.duoduo.result.Result;
import com.duoduo.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用接口")
public class CommonController {
    @Autowired  // 来自OssConfiguration的bean
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传
     * @param file: 前端从用户本地上传的文件
     * @return
     */
    @PostMapping(value = "/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传，原文件名为：{}", file.getOriginalFilename());
        try {
            // 原始文件名
            String originalFilename = file.getOriginalFilename();
            // 截取后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            // uuid构建新文件名
            String objectName = UUID.randomUUID().toString() + extension;
            // 上传到OSS，并返回访问路径
            String url = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(url);
        } catch (IOException e) {
            log.error("文件上传失败：{}",e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
